﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Loong.Model;
using com.YiXiong.XML;
using QY.Util;

namespace QYWebSiteBN
{
    public partial class Form_EditTack : Form
    {
        private readonly static string WebSiteFile = ConfigurationSettings.AppSettings["WebSiteFile"];

        private URLModelRule urlmodel;
   
        
        public Form_EditTack()
        {
            InitializeComponent();
            UpdateTask();
            UpdateWebSite();
        }

        /// <summary>
        /// 重载窗口构造函数
        /// </summary>
        /// <param name="path">传入‘网站’->‘任务’</param>
        public Form_EditTack(string path):this()
        {
            string website = QY.Util.Regular.RegularString(@"WebSites/WebSite\[@Name='(.*?)'\]", path);
            string task = QY.Util.Regular.RegularString(@"Task\[@Name='(.*?)'\]", path);
            cbWebSite.Text = website;
            txtTaskName.Text = task;
            InitUrlModelRule(website,task);
            UpdateTask();
            LoadTag();
            UpdateTagList();
           

        }

        /// <summary>
        /// 初始化地址采集规则中的地址
        /// </summary>
        protected void InitUrlModelRule(string webstie,string taskname)
        {
            if(string.IsNullOrEmpty(webstie)||string.IsNullOrEmpty(taskname))
            {
                return;
            }

            string dir=StoreDir();
            string file=string.Format("{0}\\{1}",dir,"url.task");
            urlmodel = new URLModelRule(file);
        }

        /// <summary>
        /// 提供其它窗口访问UrlModel
        /// </summary>
        public URLModelRule UrlModel
        {
            get { return this.urlmodel; }
            set { this.urlmodel = value; }
        }

 

      
        /// <summary>
        /// 更新Url地址列表
        /// </summary>
        public void UpdateTask()
        {
            lbTaskUrl.Items.Clear();
            if (urlmodel != null)
            {
                for (int i = 0; i < urlmodel.Count; i++)
                {
                    lbTaskUrl.Items.Add(urlmodel.Get(i).Name);
                }
            }
        }

        private void LoadTag()
        {
            string dir = StoreDir();
            string file = string.Format("{0}\\{1}", dir, "tag.task");
            HTMLTag.Load(file);
        }

 

        /// <summary>
        /// 更新内容规则中的标签列表
        /// </summary>
        public void UpdateTagList()
        {
            LVTag.Items.Clear();
           
           
            int count=HTMLTag.Count;
            for (int i = 0; i <count ; i++)
            {
                ListViewItem item = new ListViewItem(new string[]{HTMLTag.Get(i).Name,HTMLTag.Get(i).BeginMathing,HTMLTag.Get(i).EndMatching});

                LVTag.Items.Add(item);
            }
        }

        /// <summary>
        /// 更新网站选择框
        /// </summary>
        public void UpdateWebSite()
        {
            cbWebSite.Items.Clear();
            string file = string.Format("{0}/{1}", System.IO.Directory.GetCurrentDirectory(), WebSiteFile);
            XMLHelper helper = new XMLHelper(file);
            XmlAttributeCollection ac= helper.GetChildNodesAttributesByAttributeName("WebSites", "Name");

            foreach (XmlAttribute a in ac)
            {
                cbWebSite.Items.Add(a.Value);
            }
        }

        /// <summary>
        /// 获得当前设置的任务名
        /// </summary>
        public string TaskName()
        {
            return txtTaskName.Text;
        }


        /// <summary>
        /// 获得当前设置的网站名
        /// </summary> 
        public string WebSiteName()
        {
            return cbWebSite.Text;
        }

        /// <summary>
        /// 获得当前网站任务的存储目录
        /// </summary> 
        public string StoreDir()
        {
            string dir = System.IO.Directory.GetCurrentDirectory();
            string websitename = cbWebSite.Text;
            string task = txtTaskName.Text;

            dir = string.Format(@"{0}\website\{1}\{2}", dir, websitename, task);

            if (!System.IO.Directory.Exists(dir))
            {
                System.IO.Directory.CreateDirectory(dir);
            }

            return dir;
        }

        /// <summary>
        /// 添加地址规则
        /// </summary> 
        private void btnUrlAdd_Click(object sender, EventArgs e)
        {
            Form_AddUrl fadd = new Form_AddUrl();
            fadd.Owner = this;
            fadd.ShowDialog();
        }
       
 
        /// <summary>
        /// 添加标签
        /// </summary> 
        private void btnTagAdd_Click(object sender, EventArgs e)
        {
            Form_Tag ft = new Form_Tag();
            ft.Owner = this;
            ft.ShowDialog();
        }

        /// <summary>
        /// 编辑标签
        /// </summary> 
        private void LVTag_DoubleClick(object sender, EventArgs e)
        {
            if (LVTag.SelectedItems != null)
            {
                Form_Tag ftag = new Form_Tag(LVTag.SelectedItems[0].Index);
                ftag.Owner = this;
                ftag.ShowDialog();
            }
        }

        /// <summary>
        /// 删除标签
        /// </summary> 
        private void btnTagDelete_Click(object sender, EventArgs e)
        {
            if (LVTag.SelectedItems != null)
            {
                HTMLTag.Delete(LVTag.SelectedItems[0].Index);
            }
            UpdateTagList();
        }


        /// <summary>
        /// 创建新的任务名到xml存储文件
        /// </summary>
        /// <param name="website">网站名</param>
        /// <param name="taskname">任务名</param>
        public void CreateTask(string website,string taskname)
        {          

            if (string.IsNullOrEmpty(website))
            {
                throw new NullReferenceException("网站不能为空");
            }

            if (string.IsNullOrEmpty(taskname))
            {
                throw new NullReferenceException("任务名不能为空");
            }

            string file = string.Format("{0}/{1}", System.IO.Directory.GetCurrentDirectory(), WebSiteFile);
      

          
            XMLHelper xmlhelp = new XMLHelper(file);
            if (xmlhelp.ExistNode(string.Format("WebSites/WebSite[@Name='{0}']/Task[@Name='{1}']", website,taskname)))
            {
                return;//如果任务名存在，则退出!
            }

            XmlAttributeCollection ac = new XmlAttributeCollection();
            ac.Add(new XmlAttribute("Name", taskname));
            ac.Add(new XmlAttribute("Text", string.Empty));
            xmlhelp.AddNode(string.Format("WebSites/WebSite[@Name='{0}']", website), "Task", string.Empty, ac);       
            xmlhelp.Save();
 
        }


        public void SaveUrlRule()
        {
            string dir=StoreDir();
            string file=string.Format("{0}\\{1}",dir,"url.task");
            urlmodel.Save(file);
        }

        public void SaveTag()
        {
            string dir = StoreDir();
            string file = string.Format("{0}\\{1}", dir, "tag.task");
            HTMLTag.Save(file);
        }


        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (cbWebSite.SelectedItem == null)
            {
                MessageBox.Show("网站不能为空!");
                cbWebSite.Focus();
                return;
            }

            if (string.IsNullOrEmpty(txtTaskName.Text))
            {
                MessageBox.Show("任务名称不能为空");
                txtTaskName.Focus();
                return;
            }

            CreateTask(cbWebSite.Text, txtTaskName.Text);
            SaveUrlRule();
            SaveTag();


            Form1 f = (Form1)this.Owner;
            f.updateTask();
            HTMLTag.Clear();

            this.Close();
        }

        /// <summary>
        /// 编辑地址规则
        /// </summary>
        private void lbTaskUrl_DoubleClick(object sender, EventArgs e)
        {
            if (lbTaskUrl.SelectedItem != null)
            {
                
                Form_AddUrl fadd = new Form_AddUrl(urlmodel.Get(lbTaskUrl.SelectedIndex));
                fadd.Owner = this;
                fadd.ShowDialog();

            }
        }

        private void btnDeleteTask_Click(object sender, EventArgs e)
        {
            if (lbTaskUrl.SelectedItem != null)
            {
                urlmodel.Delete(lbTaskUrl.SelectedIndex);
            }
            UpdateTask();
        }

        private void btnSelectDir_Click(object sender, EventArgs e)
        {
            //folderBrowserDialog1.RootFolder = System.IO.Directory.GetCurrentDirectory();

            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                txtSaveDir.Text = folderBrowserDialog1.SelectedPath;
            }

        }

        private void btnTemp_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "HTML模板文件  (*.html)|*.htm";
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                
                txtTemple.Text = openFileDialog1.FileName;
               
            }
        }

       
    }
}
